﻿
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

using DotNetty.Wraper;
using Examples.Common;
using Microsoft.Extensions.Logging;

namespace TcpSocket.Server
{
    class Program
    {
        static async Task Main(string[] args)
        {
            ILogger _logger = new CNative.Logging.ConfigLogger();// LoggingHelper.Logger;

            X509Certificate2 tlsCertificate = null;
            if (ServerSettings.IsSsl)
            {
                tlsCertificate = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
            }

            var theServerBuild = SocketBuilderFactory.GetTcpSocketServerBuilder(Examples.Common.ServerSettings.Port);
            theServerBuild
             //.AddLast(new DotNetty.Handlers.Logging.LoggingHandler("SRV-CONN"))
             //.AddLast("framing-enc", new DotNetty.Codecs.LengthFieldPrepender(2))
             //.AddLast("framing-dec", new DotNetty.Codecs.LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2))
             .OnConnectionClose((server, connection) =>
             {
                 _logger.LogInformation($"连接关闭,连接名[{connection.ConnectionName}],当前连接数:{server.GetConnectionCount()}");
             })
             .OnException(ex =>
             {
                 _logger.LogError($"服务端异常:{ex.Message}");
             })
             .OnChannelRegistered((server, channel) =>
             {
                 _logger.LogDebug("ChannelUnregistered: " + channel.Id);
             })
             .OnChannelRegistered((server, channel) =>
             {
                 _logger.LogDebug("ChannelRegistered: " + channel.Id);
             })
             .OnNewConnection((server, connection) =>
             {
                 connection.ConnectionName = $"名字{connection.ConnectionId}";
                 _logger.LogInformation($"新的连接[{connection.ClientAddress.Address.MapToIPv4().ToString()}]:{connection.ConnectionName},当前连接数:{server.GetConnectionCount()}");
             })
             .OnRecieve((server, connection, bytes) =>
             {
                 _logger.LogInformation($"服务端:数据{Encoding.UTF8.GetString(bytes)}");
                 //connection.Send(bytes);
             })
             .OnSend((server, connection, bytes) =>
             {
                 _logger.LogInformation($"向连接名[{connection.ConnectionName}]发送数据:{Encoding.UTF8.GetString(bytes)}");
             })
             .OnServerStarted(server =>
             {
                 _logger.LogInformation($"服务启动");
             });
            var theServer = await theServerBuild.BuildAsync(null, (pipeline) =>
            {
                pipeline.AddLast(new DotNetty.Handlers.Logging.LoggingHandler("SRV-CONN"));
                pipeline.AddLast("framing-enc", new DotNetty.Codecs.LengthFieldPrepender(2));
                pipeline.AddLast("framing-dec", new DotNetty.Codecs.LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));
            }, ServerSettings.UseLibuv, tlsCertificate, 100, 1);
            //.BuildAsync((tcpServer) => { return new EchoServerHandler(tcpServer as IChannelEvent, ServerSettings.UseLibuv, 100, 1); });

            Console.ReadLine();

            theServer?.Close();
        }
    }
}
